<template>
  <Dialog v-model="dialogVisible" title="计划工作流" width="1200px">
    <!-- 工作流概览 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>工作流概览</span>
          <el-space>
            <el-tag :type="getWorkflowStatusColor(workflowData.status)">
              {{ getWorkflowStatusName(workflowData.status) }}
            </el-tag>
            <el-button type="primary" size="small" @click="refreshWorkflow">
              刷新状态
            </el-button>
          </el-space>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="计划名称">
          {{ workflowData.planName || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="当前阶段">
          {{ getCurrentStageName() }}
        </el-descriptions-item>
        <el-descriptions-item label="整体进度">
          <el-progress :percentage="workflowData.overallProgress" />
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ workflowData.startTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="预计结束时间">
          {{ workflowData.estimatedEndTime || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="实际结束时间">
          {{ workflowData.actualEndTime || '进行中' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <!-- 工作流步骤 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <span>工作流步骤</span>
      </template>
      
      <el-steps :active="currentStepIndex" direction="vertical" finish-status="success">
        <el-step
          v-for="(step, index) in workflowSteps"
          :key="index"
          :title="step.stepName"
          :description="step.description"
          :status="getStepStatus(step)"
        >
          <template #icon>
            <el-icon v-if="step.status === 'completed'">
              <SuccessFilled />
            </el-icon>
            <el-icon v-else-if="step.status === 'error'">
              <CircleCloseFilled />
            </el-icon>
            <el-icon v-else-if="step.status === 'processing'">
              <Loading />
            </el-icon>
            <span v-else>{{ index + 1 }}</span>
          </template>
          
          <!-- 步骤详情 -->
          <div style="margin-top: 10px;">
            <el-row :gutter="20">
              <el-col :span="8">
                <div><strong>负责人：</strong>{{ step.assignee || '-' }}</div>
              </el-col>
              <el-col :span="8">
                <div><strong>开始时间：</strong>{{ step.startTime || '-' }}</div>
              </el-col>
              <el-col :span="8">
                <div><strong>结束时间：</strong>{{ step.endTime || '-' }}</div>
              </el-col>
            </el-row>
            
            <div style="margin-top: 10px;">
              <strong>进度：</strong>
              <el-progress :percentage="step.progress" :color="getProgressColor(step.progress)" />
            </div>
            
            <!-- 操作按钮 -->
            <div style="margin-top: 10px;" v-if="step.status === 'processing' || step.status === 'pending'">
              <el-space>
                <el-button 
                  v-if="step.canStart" 
                  type="success" 
                  size="small" 
                  @click="startStep(step)"
                >
                  开始执行
                </el-button>
                <el-button 
                  v-if="step.canComplete" 
                  type="primary" 
                  size="small" 
                  @click="completeStep(step)"
                >
                  完成步骤
                </el-button>
                <el-button 
                  v-if="step.canPause" 
                  type="warning" 
                  size="small" 
                  @click="pauseStep(step)"
                >
                  暂停
                </el-button>
                <el-button 
                  v-if="step.canSkip" 
                  type="info" 
                  size="small" 
                  @click="skipStep(step)"
                >
                  跳过
                </el-button>
              </el-space>
            </div>
            
            <!-- 步骤备注 -->
            <div v-if="step.remark" style="margin-top: 10px;">
              <el-alert :title="step.remark" type="info" :closable="false" />
            </div>
          </div>
        </el-step>
      </el-steps>
    </el-card>
    
    <!-- 任务列表 -->
    <el-card style="margin-bottom: 20px;">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span>当前任务列表</span>
          <el-button type="primary" size="small" @click="refreshTasks">
            刷新任务
          </el-button>
        </div>
      </template>
      
      <el-table :data="currentTasks" style="width: 100%">
        <el-table-column prop="taskName" label="任务名称" width="200" />
        <el-table-column prop="taskType" label="任务类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ getTaskTypeName(row.taskType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assignee" label="执行人" width="120" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityColor(row.priority)">
              {{ getPriorityName(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTaskStatusColor(row.status)">
              {{ getTaskStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="dueTime" label="截止时间" width="150" />
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="{ row }">
            <el-progress :percentage="row.progress" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewTask(row)">
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="success" 
              size="small" 
              @click="startTask(row)"
            >
              开始
            </el-button>
            <el-button 
              v-if="row.status === 'processing'" 
              link 
              type="warning" 
              size="small" 
              @click="completeTask(row)"
            >
              完成
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 操作历史 -->
    <el-card>
      <template #header>
        <span>操作历史</span>
      </template>
      
      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in operationHistory"
          :key="index"
          :timestamp="record.operationTime"
          :type="getOperationTypeColor(record.operationType)"
        >
          <el-card>
            <h4>{{ record.operationName }}</h4>
            <p><strong>操作人：</strong>{{ record.operator }}</p>
            <p><strong>操作类型：</strong>{{ getOperationTypeName(record.operationType) }}</p>
            <p v-if="record.description"><strong>描述：</strong>{{ record.description }}</p>
            <p v-if="record.result"><strong>结果：</strong>{{ record.result }}</p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-card>
    
    <template #footer>
      <el-space>
        <el-button type="success" @click="approveWorkflow" v-if="canApprove">
          审批通过
        </el-button>
        <el-button type="danger" @click="rejectWorkflow" v-if="canReject">
          驳回
        </el-button>
        <el-button type="warning" @click="pauseWorkflow" v-if="canPause">
          暂停工作流
        </el-button>
        <el-button type="primary" @click="resumeWorkflow" v-if="canResume">
          恢复工作流
        </el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </el-space>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { SuccessFilled, CircleCloseFilled, Loading } from '@element-plus/icons-vue'
import { Dialog } from '@/components/Dialog'
import {
  getWorkflowDetail,
  getWorkflowSteps,
  getCurrentTasks,
  getOperationHistory
} from '@/api/eval/workflow'
import type {
  EvalWorkflowDetailVO,
  EvalWorkflowStepVO,
  EvalWorkflowTaskVO,
  EvalWorkflowOperationHistoryVO
} from '@/api/eval/workflow/types'
import { getPlan } from '@/api/eval/plan'

const dialogVisible = ref(false)
const loading = ref(false)
const planId = ref<number>(0)

const workflowData = ref<EvalWorkflowDetailVO>({
  planId: 0,
  planName: '',
  status: 'pending',
  overallProgress: 0,
  startTime: undefined,
  estimatedEndTime: undefined,
  actualEndTime: undefined,
  currentStage: '',
  currentStageName: ''
})

const workflowSteps = ref<EvalWorkflowStepVO[]>([])
const currentTasks = ref<EvalWorkflowTaskVO[]>([])
const operationHistory = ref<EvalWorkflowOperationHistoryVO[]>([])

const currentStepIndex = computed(() => {
  return workflowSteps.value.findIndex(step => step.status === 'processing')
})

const canApprove = computed(() => workflowData.value.status === 'pending_approval')
const canReject = computed(() => workflowData.value.status === 'pending_approval')
const canPause = computed(() => workflowData.value.status === 'running')
const canResume = computed(() => workflowData.value.status === 'paused')

/** 获取工作流数据 */
const getWorkflowData = async () => {
  if (!planId.value) return

  loading.value = true
  try {
    // 获取计划基本信息
    const planResult = await getPlan(planId.value)
    if (planResult.data) {
      workflowData.value.planId = planResult.data.id
      workflowData.value.planName = planResult.data.planName
      workflowData.value.status = getStatusName(planResult.data.planStatus)
      workflowData.value.startTime = planResult.data.evaluationStartDate
      workflowData.value.estimatedEndTime = planResult.data.evaluationEndDate
      workflowData.value.currentStage = getCurrentStageFromStatus(planResult.data.planStatus)
      workflowData.value.overallProgress = calculateProgress(planResult.data.planStatus)
    }

    // 获取工作流步骤
    try {
      const stepsResult = await getWorkflowSteps(planId.value)
      workflowSteps.value = stepsResult.data || []
    } catch (error) {
      console.warn('获取工作流步骤失败:', error)
      workflowSteps.value = []
    }

    // 获取当前任务
    try {
      const tasksResult = await getCurrentTasks(planId.value)
      currentTasks.value = tasksResult.data || []
    } catch (error) {
      console.warn('获取当前任务失败:', error)
      currentTasks.value = []
    }

    // 获取操作历史
    try {
      const historyResult = await getOperationHistory(planId.value)
      operationHistory.value = historyResult.data || []
    } catch (error) {
      console.warn('获取操作历史失败:', error)
      operationHistory.value = []
    }

  } catch (error) {
    console.error('获取工作流数据失败:', error)
    ElMessage.error('获取工作流数据失败')
  } finally {
    loading.value = false
  }
}

/** 根据状态码获取状态名称 */
const getStatusName = (status: number) => {
  const statusMap = {
    0: 'draft',
    1: 'pending_approval',
    2: 'running',
    3: 'paused',
    4: 'completed',
    5: 'cancelled'
  }
  return statusMap[status] || 'unknown'
}

/** 根据状态获取当前阶段 */
const getCurrentStageFromStatus = (status: number) => {
  const stageMap = {
    0: 'planning',
    1: 'approval',
    2: 'evaluation',
    3: 'paused',
    4: 'completed',
    5: 'cancelled'
  }
  return stageMap[status] || 'unknown'
}

/** 计算进度 */
const calculateProgress = (status: number) => {
  const progressMap = {
    0: 10,  // 草稿
    1: 30,  // 待审批
    2: 70,  // 进行中
    3: 70,  // 暂停
    4: 100, // 已完成
    5: 0    // 已取消
  }
  return progressMap[status] || 0
}

const getCurrentStageName = () => {
  const stageMap = {
    'planning': '计划阶段',
    'registration': '报名阶段',
    'allocation': '分配阶段',
    'evaluation': '评价阶段',
    'scoring': '成绩阶段',
    'publicity': '公示阶段',
    'completed': '已完成'
  }
  return stageMap[workflowData.value.currentStage] || '未知阶段'
}

const getWorkflowStatusName = (status: string) => {
  const statusMap = {
    'draft': '草稿',
    'pending_approval': '待审批',
    'running': '运行中',
    'paused': '已暂停',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

const getWorkflowStatusColor = (status: string) => {
  const colorMap = {
    'draft': 'info',
    'pending_approval': 'warning',
    'running': 'success',
    'paused': 'warning',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return colorMap[status] || 'info'
}

const getStepStatus = (step: any) => {
  const statusMap = {
    'completed': 'success',
    'processing': 'process',
    'pending': 'wait',
    'error': 'error'
  }
  return statusMap[step.status] || 'wait'
}

const getProgressColor = (progress: number) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 50) return '#e6a23c'
  return '#f56c6c'
}

const getTaskTypeName = (type: string) => {
  const typeMap = {
    'supervision': '监督检查',
    'inspection': '设备检查',
    'objection': '异议处理',
    'scoring': '成绩录入',
    'review': '材料审核'
  }
  return typeMap[type] || type
}

const getPriorityName = (priority: string) => {
  const priorityMap = { 'high': '高', 'medium': '中', 'low': '低' }
  return priorityMap[priority] || priority
}

const getPriorityColor = (priority: string) => {
  const colorMap = { 'high': 'danger', 'medium': 'warning', 'low': 'success' }
  return colorMap[priority] || 'info'
}

const getTaskStatusName = (status: string) => {
  const statusMap = {
    'pending': '待执行',
    'processing': '进行中',
    'completed': '已完成',
    'paused': '已暂停'
  }
  return statusMap[status] || status
}

const getTaskStatusColor = (status: string) => {
  const colorMap = {
    'pending': 'warning',
    'processing': 'primary',
    'completed': 'success',
    'paused': 'info'
  }
  return colorMap[status] || 'info'
}

const getOperationTypeName = (type: string) => {
  const typeMap = {
    'start': '开始',
    'complete': '完成',
    'pause': '暂停',
    'resume': '恢复',
    'approve': '审批',
    'reject': '驳回'
  }
  return typeMap[type] || type
}

const getOperationTypeColor = (type: string) => {
  const colorMap = {
    'start': 'primary',
    'complete': 'success',
    'pause': 'warning',
    'resume': 'primary',
    'approve': 'success',
    'reject': 'danger'
  }
  return colorMap[type] || 'primary'
}

const refreshWorkflow = () => {
  ElMessage.success('工作流状态已刷新')
}

const refreshTasks = () => {
  ElMessage.success('任务列表已刷新')
}

const startStep = (step: any) => {
  step.status = 'processing'
  step.startTime = new Date().toLocaleString()
  ElMessage.success(`步骤"${step.stepName}"已开始`)
}

const completeStep = (step: any) => {
  step.status = 'completed'
  step.progress = 100
  step.endTime = new Date().toLocaleString()
  ElMessage.success(`步骤"${step.stepName}"已完成`)
}

const pauseStep = (step: any) => {
  step.status = 'paused'
  ElMessage.warning(`步骤"${step.stepName}"已暂停`)
}

const skipStep = (step: any) => {
  step.status = 'skipped'
  step.progress = 100
  ElMessage.info(`步骤"${step.stepName}"已跳过`)
}

const viewTask = (task: any) => {
  ElMessage.info(`查看任务: ${task.taskName}`)
}

const startTask = (task: any) => {
  task.status = 'processing'
  task.startTime = new Date().toLocaleString()
  ElMessage.success(`任务"${task.taskName}"已开始`)
}

const completeTask = (task: any) => {
  task.status = 'completed'
  task.progress = 100
  ElMessage.success(`任务"${task.taskName}"已完成`)
}

const approveWorkflow = () => {
  workflowData.value.status = 'running'
  ElMessage.success('工作流审批通过')
}

const rejectWorkflow = () => {
  workflowData.value.status = 'rejected'
  ElMessage.error('工作流已驳回')
}

const pauseWorkflow = () => {
  workflowData.value.status = 'paused'
  ElMessage.warning('工作流已暂停')
}

const resumeWorkflow = () => {
  workflowData.value.status = 'running'
  ElMessage.success('工作流已恢复')
}

const open = (planData?: any) => {
  dialogVisible.value = true
  if (planData) {
    // 如果传入的是完整的计划对象，直接使用其数据
    if (planData.id) {
      planId.value = planData.id
      // 先设置基本信息，避免显示空白
      workflowData.value.planId = planData.id
      workflowData.value.planName = planData.planName || ''
      workflowData.value.status = getStatusName(planData.planStatus || 0)
      workflowData.value.overallProgress = calculateProgress(planData.planStatus || 0)
      workflowData.value.startTime = planData.evaluationStartDate || ''
      workflowData.value.estimatedEndTime = planData.evaluationEndDate || ''
      workflowData.value.currentStage = getCurrentStageFromStatus(planData.planStatus || 0)
      workflowData.value.currentStageName = getCurrentStageName()

      // 然后获取详细的工作流数据
      getWorkflowData()
    }
  }
}

defineExpose({ open })
</script>
